package com.zhiwei.common.util;

import org.springframework.http.HttpMethod;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * function: http工具类
 * author: zhiwei_yang
 * time: 2020/2/12-15:40
 */
public class HttpUtil {

    /**
     * 获取请求参数
     *
     * @param httpServletRequest
     * @return
     */
    public static String getRequestParamsStr(HttpServletRequest httpServletRequest) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        if (HttpMethod.GET.name().equals(httpServletRequest.getMethod())) {
            Map<String, String> requestMap = new HashMap<>();
            Enumeration<String> enumeration = httpServletRequest.getParameterNames();
            while (enumeration.hasMoreElements()) {
                String paramName = enumeration.nextElement();
                requestMap.put(paramName, httpServletRequest.getParameter(paramName));
            }
            stringBuilder.append(requestMap.toString());
        }

        if (HttpMethod.POST.name().equals(httpServletRequest.getMethod())) {
            InputStream inputStream = httpServletRequest.getInputStream();
            stringBuilder.append(StreamUtils.copyToString(inputStream, Charset.defaultCharset()));
        }
        return stringBuilder.toString();
    }

    /**
     * 获取请求头参数
     *
     * @param httpServletRequest
     * @return
     */
    public static Map<String, String> getRequestHeaderMap(HttpServletRequest httpServletRequest) {
        Map<String, String> headerMap = new HashMap<>();
        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headerMap.put(headerName, httpServletRequest.getHeader(headerName));
        }
        return headerMap;
    }
}
